package com.baizw.cultivation.module.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baizw.cultivation.constant.CommonConstants;
import com.baizw.cultivation.security.service.SecurityService;
import com.baizw.cultivation.module.admin.entity.RoleEntity;
import com.baizw.cultivation.module.admin.entity.UserEntity;
import com.baizw.cultivation.module.admin.entity.vo.UserMenu;
import com.baizw.cultivation.module.admin.service.ResourceService;
import com.baizw.cultivation.module.admin.service.RoleService;
import com.baizw.cultivation.module.admin.service.UserService;
import com.baizw.cultivation.util.PermissionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 安全授权接口实现
 *
 * @author 剧终1204
 * @version V1.0
 * @date 2020年06月11日 16:03
 */
@Slf4j
@Service
public class SecurityServiceImpl implements SecurityService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;

    @Override
    @Cacheable(value = CommonConstants.LOGIN_USER_ROLE_CACHE, key = "'Roles_'+#userId")
    public Set<String> roles(Long userId) {
        UserEntity userEntity = userService.getById(userId);
        if (ObjectUtil.isNull(userEntity)) {
            log.error("ID为{}的用户不存在", userId);
            return CollUtil.newHashSet();
        }
        Long roleId = userEntity.getRoleId();
        RoleEntity roleEntity = roleService.getById(roleId);
        return CollUtil.newHashSet(roleEntity.getName());
    }

    @Override
    @Cacheable(value = CommonConstants.LOGIN_USER_PERMISSION_CACHE, key = "'Permissions_'+#userId")
    public Set<String> stringPermissions(Long userId) {
        List<UserMenu> resourceList = resourceService.listResource(userId);
        return PermissionUtil.hasPermission(resourceList);
    }
}
